package com.sinochem.sales.service.controller;

import com.sinochem.sales.common.api.to.sms.SendSmsTo;
import com.sinochem.sales.common.api.vo.SendSmsinfoVO;
import com.sinochem.sales.common.constant.CacheConstant;
import com.sinochem.sales.common.constant.MqQueueConstant;
import com.sinochem.sales.common.constant.SecurityConstants;
import com.sinochem.sales.common.entity.Result;
import com.sinochem.sales.common.util.AssertUtils;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * @author xuan😴🐶🐱🐽🌺  <a href="zhangshixuanj@163.com">联系作者</a>
 * @version Revision:v1.0,Date: 2018/4/16 14:30
 * @project sinochem-ubmp-registry
 * @description
 * @Modification Date: 2018/4/16 14:30  {填写修改说明}
 */
@Slf4j
@RestController
@RequestMapping("sms")
@Api(tags = "短信")
public class SMSController {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 短信验证码
     *
     * @param sendSmsTo
     * @return
     */
    @PostMapping(value = "sendSMSCode")
    public Result<String> sendSMSCode(@RequestBody SendSmsTo sendSmsTo) {
        String re = (String) redisTemplate.opsForValue().get(CacheConstant.SEND_CODE_KEY + sendSmsTo.getMobile());
        AssertUtils.notBlank(re, "验证码未使用");
        String text = (String) redisTemplate.opsForValue().get(SecurityConstants.IMG_CODE_KEY + sendSmsTo.getText());
        AssertUtils.notBlank(text, "验证码失效");
        AssertUtils.equals(text, sendSmsTo.getText(), "验证码错误");
        SendSmsinfoVO sendSmsinfoVO = new SendSmsinfoVO();
        sendSmsinfoVO.setMobile(sendSmsTo.getMobile());
        //TODO 设置模板
        rabbitTemplate.convertAndSend(MqQueueConstant.MOBILE_CODE_QUEUE, sendSmsinfoVO);
        redisTemplate.opsForValue().set(CacheConstant.SEND_CODE_KEY + sendSmsTo.getMobile(), text, SecurityConstants.DEFAULT_IMAGE_EXPIRE, TimeUnit.SECONDS);
        return Result.success("发送短信成功");
    }
}
